package com.bg.rpc.zk;

import com.bg.rpc.constant.Constant;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Auther: zhengshunzhi
 * @Date: 2018/8/24 22:40
 * @Description: 寻找和发现zookeeper /registry目录下的服务 服务发现:连接ZK,添加watch事件
 */
public class ServiceDiscovery {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceDiscovery.class);

    //计数器
    private final CountDownLatch latch = new CountDownLatch(1);

    //存储节点数据
    private static volatile List<String> dataList = new ArrayList<>();

    //连接ip和端口
    private final String registryAddress;

    //zk对象
    private static ZooKeeper zk;

    //当前索引
    private static volatile int currentIndex;

    public ServiceDiscovery(String registryAddress) {
        this.registryAddress = registryAddress;
        //连接zk
        connectServer();

        if (zk != null) {
            //监测zk节点变化
            watchNode(zk);
        }
    }

    /**
     * 功能描述: 返回zk节点下的数据
     *
     * @param:
     * @return:
     * @auther: bonree
     * @date: 2018/8/29 10:38
     */
    public String discover() {
        String data = null;
        int size = dataList.size();
        if (size > 0) {
            //当list的长度为1的时候，获取下标为0的数据
            if (size == 1) {
                data = dataList.get(size - 1);
                LOGGER.debug("using only data: {}", data);
            } else {
                //hreadLocalRandom.current().nextInt(size)  当前集合长度的随机数
                data = dataList.get((currentIndex + 1) % dataList.size());
                LOGGER.debug("using random data: {}", data);
            }
        }
        return data;
    }

    /**
     * 功能描述:连接zk的方法
     *
     * @auther: bonree
     * @date: 2018/8/29 10:32
     */
    private ZooKeeper connectServer() {
        try {
            zk = new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    if (event.getState() == Event.KeeperState.SyncConnected) {
                        latch.countDown();
                    }
                }
            });
            latch.await();
        } catch (Exception e) {
            LOGGER.error("zk连接失败：", e);
        }
        return zk;
    }

    private void watchNode(final ZooKeeper zk) {
        try {
            List<String> nodeList = zk.getChildren(Constant.ZK_REGISTRY_PATH, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    //如果子节点发生了变化
                    if (event.getType() == Event.EventType.NodeChildrenChanged) {
                        //则递归调用
                        watchNode(zk);
                    }
                }
            });
            //获取子节点中的数据
            List<String> dataList = new ArrayList<>();
            for (String node : nodeList) {
                byte[] bytes = zk.getData(Constant.ZK_REGISTRY_PATH + "/" + node, false, null);
                dataList.add(new String(bytes));
            }
            LOGGER.debug("node data: {}", dataList);
            this.dataList = dataList;

            if (!dataList.isEmpty()) {
                //获取当前查询索引
                currentIndex = dataList.size() - 1;
            }
        } catch (Exception e) {
            LOGGER.error("error", e);
        }
    }
}
